
<template>
  <div class="permission-container">
    <div style="margin-bottom: 20px">
      <el-button
        type="primary"
        @click="dialogVisible = true"
      >添加权限</el-button>
    </div>
    <el-table
      :data="tableData"
      style="width: 100%; margin-bottom: 20px"
      row-key="id"
      border
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column prop="name" label="名称" />
      <el-table-column prop="code" label="标识" />
      <el-table-column prop="description" label="描述" />
      <el-table-column label="操作">
        <template v-slot="{ row }">
          <el-button type="text" @click="handleAdd(2, row.id)">添加</el-button>
          <el-button type="text" @click="handleEdit(row.id)">编辑</el-button>
          <el-button type="text" @click="handleDelete(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <PermissonDialog
      ref="dialog"
      :edit-id="editId"
      :list="tableData"
      :son-data="sonData"
      :dialog-visible.sync="dialogVisible"
      @okk="getPermissionList"
    />
  </div>
</template>
<script>
import { getPermissionListRequest, deletePermissionRequest } from '@/api/permission'
import { transformListTotree } from '@/utils'
import PermissonDialog from './components/PermissonDialog.vue'

export default {
  name: 'PermissionCom',
  components: {
    PermissonDialog
  },
  data() {
    return {
      tableData: [],
      dialogVisible: false,
      sonData: {
        pid: null,
        type: null
      },
      editId: null
    }
  },
  watch: {
    dialogVisible(val) {
      if (!val) {
        this.sonData = {
          pid: null,
          type: null
        }
        this.editId = null
      }
    }
  },
  created() {
    this.getPermissionList()
  },
  methods: {
    async getPermissionList() {
      const res = await getPermissionListRequest()
      // 平铺数据转换为tree树形数据--- 带有children
      this.tableData = transformListTotree(res.data, 0)
    },
    handleDelete(id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await deletePermissionRequest(id)
        this.$message({
          type: 'success',
          message: res.message
        })
        this.getPermissionList()
      })
    },
    handleAdd(type, pid) {
      this.dialogVisible = true
      this.sonData.type = type
      this.sonData.pid = pid
    },
    handleEdit(id) {
      this.dialogVisible = true
      this.editId = id
      this.$refs.dialog.getPermissionDetail(id)
    }
  }
}
</script>

<style lang="scss" scoped>
.permission-container {
  padding: 20px;
}
</style>
